
/** 
 * H5压缩 二分查找算法来找到一个合适的图像质量系数，使得压缩后的图片文件大小接近于目标大小
 * @param {Object} imgSrc 图片url 
 * @param {Object} callback 回调设置返回值 
 * */
export function compressH5(fileItem, targetSizeKB, initialQuality = 1.0) {
  const maxQuality = 1.0;
  const minQuality = 0.0;
  const tolerance = 0.01; // 根据需要调整公差
  return new Promise((resolve, reject) => {
      const binarySearch = (min, max) => {
          const midQuality = (min + max) / 2;

          const reader = new FileReader();
          reader.readAsDataURL(fileItem);
          reader.onload = function () {
              const img = new Image();
              img.src = this.result;
              img.onload = function () {
                  const canvas = document.createElement('canvas');
                  const ctx = canvas.getContext('2d');

                  canvas.width = img.width;
                  canvas.height = img.height;

                  ctx.clearRect(0, 0, canvas.width, canvas.height);
                  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                  // 使用异步的 toBlob 方法
                  canvas.toBlob(async (blob) => {
                      const fileSizeKB = blob.size / 1024;

                      if (Math.abs(fileSizeKB - targetSizeKB) < tolerance || max - min < tolerance) {
                          // 当前质量足够接近目标大小，使用当前质量解析
                          resolve(URL.createObjectURL(blob));
                      } else if (fileSizeKB > targetSizeKB) {
                          // 如果文件大小太大，降低质量，继续二分查找
                          binarySearch(min, midQuality);
                      } else {
                          // 如果文件大小太小，增加质量，继续二分查找
                          binarySearch(midQuality, max);
                      }
                  }, 'image/jpeg', midQuality);
              };
          };
          reader.onerror = function (error) {
              reject(error);
          };
      };

      // 开始二分查找
      binarySearch(minQuality, maxQuality);
  });
}



// app 或小程序压缩图片
// 压缩图片
export function compressImage(filePath, quality, successCallback, errorCallback) {
  uni.compressImage({
      src: filePath,
      quality: quality,
      success: (res) => {
          successCallback(res.tempFilePath);
      },
      fail: (err) => {
          errorCallback(err);
      }
  });
}

// 二分查找压缩质量
export function binarySearchCompress(filePath, targetSize, low, high, successCallback, errorCallback) {
  if (low > high) {
      errorCallback("无法达到目标大小");
      return;
  }

  const mid = Math.floor((low + high) / 2);

  compressImage(filePath, mid, (tempFilePath) => {
      uni.getFileInfo({
          filePath: tempFilePath,
          success: (res) => {
              const currentSize = res.size;
                console.log('currentSize',currentSize,',targetSize',targetSize)
              if (currentSize <= targetSize) {
                  successCallback(tempFilePath);
              } else {
                  // 递归调整压缩质量
                  binarySearchCompress(filePath, targetSize, low, mid - 10, successCallback, errorCallback);
              }
          },
          fail: (err) => {
              errorCallback(err);
          }
      });
  }, (err) => {
      errorCallback(err);
  });
}

 // 小程序 或 App
/**
  * 递归压缩微信图片
  * @param url 图片路径
  * @param count 已递归次数（有可能压缩不到想要的大小，所以得限制次数）
  * @param isReturnBase64 是否返回base64
  * @param callback 回调函数
  * @param errorCallback 错误的回调函数
  * @return
  */
export function recursionCompress(url, count, isReturnBase64, callback,errorCallback) {
    // 在递归五次后结束递归
    if (count > 5) {
      if (isReturnBase64) {
        WechatTobase4(url)
      } else {
        callback && callback(url);
      }
      return;
    }
    let fileSystemManager=''
    // #ifdef MP-WEIXIN
    fileSystemManager = wx.getFileSystemManager();
    // #endif
    // #ifdef APP-PLUS
    fileSystemManager = uni;
    // #endif
    // 将图片进行压缩
    uni.compressImage({
      src: url, // 图片路径
      quality: 40, // 压缩质量
      success: (resCompress) => {
        console.log(resCompress, "压缩后");
        // 先获取压缩后的体积，大于1M就继续压缩
        fileSystemManager.getFileInfo({
          filePath: resCompress.tempFilePath,
          success: (resFileInfo) => {
            if (resFileInfo.size > 1024 * 1024) {
              //压缩后大于1M就继续压缩
              count++;
              recursionCompress(resCompress.tempFilePath, count, isReturnBase64, callback);
              return;
            } else {
              if (isReturnBase64) {
                WechatTobase4(resCompress.tempFilePath)
              } else {
                console.log('压缩成功，压缩后size:',resFileInfo.size / 1024 /1024,',压缩后图片路径:',resCompress.tempFilePath)
                callback && callback(resCompress.tempFilePath)
              }
            }
          },
        });
      },
      fail: (err) => {
        errorCallback(err);
      },
    });
     
    // 微信-url转base64
    function WechatTobase4(url) {
      uni.getFileSystemManager().readFile({
        filePath: url, //选择图片返回的相对路径
        encoding: "base64", //编码格式
        success: async (res) => {
          callback && callback("data:image/" + "png" + ";base64," + res.data);
        },
        fail: (res) => {
          console.log(res, "wxPathTobase64-error");
          errorCallback(res);
        },
      });
    }
  }




